import Flutter
import AVFoundation

/// `AudioCaptureEventStreamHandler` is a class that handles the event stream for audio capture.
public class AudioCaptureEventStreamHandler: NSObject, FlutterStreamHandler {
    /// `audioCapture` is an instance of `AudioCapture` used for audio capture.
    private let audioCapture = AudioCapture()
    
    /// `eventSink` is a closure that sends events to the Flutter side.
    private var eventSink: FlutterEventSink?
    
    /// `onListen` is a method that is called when the Flutter side starts listening to the event stream.
    /// It sets up the audio capture session and starts sending audio data to the Flutter side.
    /// - Parameters:
    ///   - arguments: The arguments from the Flutter side.
    ///   - events: The event sink to send events to the Flutter side.
    /// - Returns: A FlutterError if there was an error, or nil if successful.
    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events
        
        guard let args = arguments as? [String: Any],
              let sampleRate = args["sampleRate"] as? Double,
              let bufferSize = args["bufferSize"] as? UInt32 else {
            return FlutterError(code: "INVALID_ARGUMENTS",
                                message: "Missing required arguments: sampleRate, bufferSize",
                                details: nil)
        }
        
        do {
            // 启动音频捕获会话
            try audioCapture.startSession(bufferSize: bufferSize, sampleRate: sampleRate) { [weak self] (data, actualSampleRate, error) in
                guard let self = self, let sink = self.eventSink else { return }
                
                if let error = error {
                    sink(FlutterError(code: "AUDIO_CAPTURE_ERROR",
                                     message: error.localizedDescription,
                                     details: nil))
                    return
                }
                
                guard let audioData = data else {
                    sink(FlutterError(code: "NO_AUDIO_DATA",
                                     message: "No audio data received",
                                     details: nil))
                    return
                }
                
                // 使用主线程发送事件，避免多线程问题
                DispatchQueue.main.async {
                    // 直接发送Float数组，而不是转换为NSNumber数组
                    // Flutter端会将其识别为Float64List
                    sink([
                        "audioData": audioData,
                        "actualSampleRate": actualSampleRate
                    ])
                }
            }
        } catch {
            return FlutterError(code: "AUDIO_CAPTURE_SETUP_ERROR",
                               message: error.localizedDescription,
                               details: nil)
        }
        
        return nil
    }
    
    /// `onCancel` is a method that is called when the Flutter side stops listening to the event stream.
    /// It stops the audio capture session.
    /// - Parameter arguments: The arguments from the Flutter side.
    /// - Returns: A FlutterError if there was an error, or nil if successful.
    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        // 停止音频捕获会话
        audioCapture.stopSession()
        eventSink = nil
        return nil
    }
}
